package com.fary.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 动态定时任务的线程池
 **/
@EnableAsync
@EnableScheduling
@Configuration
public class ScheduledConfig {

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(5);
        scheduler.setThreadNamePrefix("fary-task-");
        scheduler.setRemoveOnCancelPolicy(true);
        /**设置为false,关闭线程池中的任务时,直接执行shutdownNow() 延时关闭 开启*/
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.afterPropertiesSet();
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//线程池对拒绝任务（无线程可用的）的处理策略
        scheduler.setErrorHandler(new SchedulerErrorHandler());
        return scheduler;
    }

}

